package cn.afactory.tygz.ui.base.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.TopicType;
import cn.afactory.tygz.controller.CommunityController;
import cn.afactory.tygz.model.AdInfo;
import cn.afactory.tygz.model.AdInfoList;
import cn.afactory.tygz.model.SnsTopicInfo;
import cn.afactory.tygz.model.SnsTopicInfoList;
import cn.afactory.tygz.ui.activities.TopicAddActivity;
import cn.afactory.tygz.ui.activities.TopicDetailActivity;
import cn.afactory.tygz.ui.adapter.CommTopicListAdapter;
import cn.afactory.tygz.ui.base.entity.CommunityInfo;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.views.BannerView;
import cn.afactory.tygz.ui.base.views.CommunityGridView;
import cn.afactory.tygz.ui.base.views.search.SearchNavigationView;
import cn.afactory.tygz.ui.base.views.search.SearchSourcePager;
import cn.afactory.tygz.ui.fragments.BaseTabFragment;
import cn.afactory.tygz.ui.sns.controller.SnsControler;


public class CommunityFragment extends BaseTabFragment implements BannerView.OnBannerClickListener{

    private static final String TAG = CommunityFragment.class.getSimpleName();
    private BannerView mBannerView;
    private CommunityGridView mCommunityGridView;

    private CommunityController mController;
    private SnsControler mSnsController;

    private LinearLayout ll_banner;
    private LinearLayout ll_near_by_entrance;
    private LinearLayout ll_recomm_topic_more;
    private RelativeLayout rl_recomm_topic_more;
    private ListView lv_recomm_topic;
    private LinearLayout ll_hot_topic_more;
    private RelativeLayout rl_hot_topic_more;
    private ListView lv_hot_topic;
    private SearchNavigationView search_view;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mController == null) {
            mController = new CommunityController(mContext, mUIHandler, null);
        }

        if (mSnsController == null) {
            mSnsController = new SnsControler(mContext, mUIHandler, null);
        }

        initAd();
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case CommunityController.MSG_GET_AD_LIST_OK:
                if (msg.arg1 != 0) {

                } else {
                    if (msg.obj instanceof AdInfoList) {
                        onBannerDataLoaded((AdInfoList)msg.obj);
                    }
                }
                break;
            case CommunityController.MSG_GET_AD_LIST_KO:
                break;
            case CommunityController.MSG_GET_RECOMM_TOPIC_LIST_OK:
                handleRecommTopicList((SnsTopicInfoList)msg.obj);
                mController.doGetHotTopicList(mPageIndex,mPageSize);
                break;
            case CommunityController.MSG_GET_RECOMM_TOPIC_LIST_KO:
                break;
            case CommunityController.MSG_GET_HOT_TOPIC_LIST_OK:
                handleHotTopicList((SnsTopicInfoList)msg.obj);
                break;
            case CommunityController.MSG_GET_HOT_TOPIC_LIST_KO:
                break;
            case SnsControler.MSG_FOLLOWED_TOPIC_KO:
            case SnsControler.MSG_FOLLOWED_TOPIC_OK:
            case SnsControler.MSG_UNFOLLOWED_TOPIC_KO:
            case SnsControler.MSG_UNFOLLOWED_TOPIC_OK:
                hideLoadingView();
                break;
        }
    }

    private void handleRecommTopicList(SnsTopicInfoList t){
        if(t == null || t.value.size() == 0){
            return ;
        }
        final CommTopicListAdapter adapter = new CommTopicListAdapter(mContext,t.value);
        adapter.setOnFollowClickListener(new CommTopicListAdapter.OnFollowClickListener() {
            @Override
            public void onClickFollowButton(TextView follow, SnsTopicInfo snsTopicInfo) {
                if (snsTopicInfo.isAttentioned) {
                    showLoadingView(mContext.getString(R.string.dlg_msg_cancling_attention));
                    mSnsController.doUnFollowTopic(follow, snsTopicInfo);
                } else {
                    showLoadingView("关注中...");
                    mSnsController.doFollowTopic(follow, snsTopicInfo);
                }
            }

            @Override
            public void onClickSubjectList(String str) {

            }
        });
        lv_recomm_topic.setAdapter(adapter);
        lv_recomm_topic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, TopicDetailActivity.class);
                SnsTopicInfo snsTopicInfo = (SnsTopicInfo) adapter.getItem(position);
                intent.putExtra(TopicDetailActivity.EXT_DATA_TAG, snsTopicInfo);
                startActivity(intent);
            }
        });
        setListViewHeightBasedOnChildren(lv_recomm_topic);
    }

    private void handleHotTopicList(SnsTopicInfoList t){
        if(t == null || t.value.size() == 0){
            return ;
        }
        final CommTopicListAdapter adapter = new CommTopicListAdapter(mContext,t.value);
        adapter.setOnFollowClickListener(new CommTopicListAdapter.OnFollowClickListener() {
            @Override
            public void onClickFollowButton(TextView follow, SnsTopicInfo snsTopicInfo) {
                if (snsTopicInfo.isAttentioned) {
                    mSnsController.doUnFollowTopic(follow, snsTopicInfo);
                } else {
                    mSnsController.doFollowTopic(follow, snsTopicInfo);
                }
            }

            @Override
            public void onClickSubjectList(String str) {

            }
        });
        lv_hot_topic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, TopicDetailActivity.class);
                SnsTopicInfo snsTopicInfo = (SnsTopicInfo) adapter.getItem(position);
                intent.putExtra(TopicDetailActivity.EXT_DATA_TAG, snsTopicInfo);
                startActivity(intent);
            }
        });
        lv_hot_topic.setAdapter(adapter);
        setListViewHeightBasedOnChildren(lv_hot_topic);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        loadDataFromCashe();
    }

    @Override
    public void onResume() {
        super.onResume();
        startLoadData();
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_community, null);
        initView(view);

        setTitle(mContext.getString(R.string.title_label_comm));
        setRightButton("创建话题", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, TopicAddActivity.class);
                startActivity(intent);
            }
        });
        return view;
    }

    private int mPageIndex = 1;
    private int mPageSize = 10;
    private void startLoadData() {
        mController.doGetRecommTopicList(mPageIndex, mPageSize);
    }

    /**
     * 加载banner数据完成
     *
     * @param adInfoList
     */
    private void onBannerDataLoaded(AdInfoList adInfoList) {
        mBannerView.setBannerList(adInfoList);
        mBannerView.setOnBannerClickListener(this);
    }

    private void loadDataFromCashe() {
        mController.loadDataFromCache();
    }

    private void initView(View view) {
        ll_banner = (LinearLayout)view.findViewById(R.id.ll_banner);
        ll_near_by_entrance = (LinearLayout)view.findViewById(R.id.ll_near_by_entrance);
        rl_recomm_topic_more = (RelativeLayout)view.findViewById(R.id.rl_recomm_topic_more);
        ll_recomm_topic_more = (LinearLayout)view.findViewById(R.id.ll_recomm_topic_more);
        lv_recomm_topic = (ListView)view.findViewById(R.id.lv_recomm_topic);
        rl_hot_topic_more = (RelativeLayout)view.findViewById(R.id.rl_hot_topic_more);
        ll_hot_topic_more = (LinearLayout)view.findViewById(R.id.ll_hot_topic_more);
        lv_hot_topic = (ListView)view.findViewById(R.id.lv_hot_topic);
        search_view = (SearchNavigationView)view.findViewById(R.id.search_view);

        createSearchView();
        mBannerView = new BannerView(mContext, null, null);
        ll_banner.addView(mBannerView);
        createCommunityGridView();

        rl_recomm_topic_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NaviUtils.gotoTopicList(getActivity(), TopicType.RECOMMAND);
            }
        });

        rl_hot_topic_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NaviUtils.gotoTopicList(getActivity(),TopicType.HOT);
            }
        });
    }

    private void createCommunityGridView() {
        List<CommunityInfo> communityInfoList = new ArrayList<CommunityInfo>();
        CommunityInfo canYin = new CommunityInfo();
        canYin.name = "餐饮";
        canYin.icon = R.drawable.canyin;
        communityInfoList.add(canYin);
        CommunityInfo gongYu = new CommunityInfo();
        gongYu.name = "人才公寓";
        gongYu.icon = R.drawable.gongyu;
        communityInfoList.add(gongYu);
        CommunityInfo wuPin = new CommunityInfo();
        wuPin.name = "二手物品";
        wuPin.icon = R.drawable.wupin;
        communityInfoList.add(wuPin);
        CommunityInfo yuLe = new CommunityInfo();
        yuLe.name = "娱乐场所";
        yuLe.icon = R.drawable.yule;
        communityInfoList.add(yuLe);
        CommunityInfo jingDian = new CommunityInfo();
        jingDian.name = "周边景点";
        jingDian.icon = R.drawable.jingdian;
        communityInfoList.add(jingDian);
        CommunityInfo fuWu = new CommunityInfo();
        fuWu.name = "生活服务";
        fuWu.icon = R.drawable.fuwu;
        communityInfoList.add(fuWu);

        mCommunityGridView = new CommunityGridView(mContext, null, communityInfoList);
        ll_near_by_entrance.addView(mCommunityGridView);
    }

    private void createSearchView() {
        search_view.setSearchSourcePager(SearchSourcePager.TOPIC);
    }

    /**
     * 加载广告
     */
    private void initAd(){
        mController.doLoadCommAds();
    }

    @Override
    public void onBannerClick(AdInfo adInfo) {
        if (adInfo.advType == 1) {
            //话题
            NaviUtils.gotoTopicDetailActivity(mContext, adInfo.topicId);
        } else {
            //url
            NaviUtils.gotoWebView(mContext, adInfo.link);
        }
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        CommTopicListAdapter listAdapter = (CommTopicListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
